<template>
  <div style="width:100%">
    <form method="post" enctype="multipart/form-data" style="display:none">
      <input :id="uuid" name="file" type="file" ref="userfile" @change="selectFile" :accept="acceptType">
    </form>

    <label :for="uuid" v-if="result.length < multi && accept!=='image'" class="upload-button">
      <span></span>
      <em>{{title}}</em>
      <el-progress :text-inside="true"
                   :stroke-width="15"
                   :percentage="uploadPercent" style="margin: 10px;"
                   v-if="uploadStatus === 1"></el-progress>
    </label>

    <div class="preview">
      <div class="audio-preview" v-if="result.length && accept === 'audio'">
        <audio-player :source="result[0] | fullImagePath" style="margin-top: 20px;"></audio-player>
        <close-btn class="delete-btn" @click.native="clean"></close-btn>
      </div>
      <div class="video-preview" v-if="result.length && accept === 'video'">
        <my-video :sources="videoSource"></my-video>
        <close-btn class="delete-btn" @click.native="clean"></close-btn>
      </div>
    </div>

  </div>
</template>
<script>
/* eslint-disable no-undef */
import { mapGetters } from "vuex";

import AudioPlayer from "@/components/audio-player";
import MyVideo from "@/components/my-video";
import CloseBtn from "@/components/close-btn";
// import FileAPI from 'fileapi/dist/FileAPI.html5'
import md5 from "js-md5";
import axios from "axios";

const axiosInstance = axios.create({});
import Api from "api/api";

export default {
  props: {
    value: String,
    maxSize: {
      type: Number,
      default: 512
    },
    accept: String,
    title: {
      type: String,
      default: "上传文件"
    },
    width: Number,
    height: Number,
    multi: {
      type: Number,
      default: 1
    }
  },
  created() {
    this.uuid = Math.random()
      .toString(36)
      .substring(3, 8);
  },
  mounted() {
    if (this.value.length) {
      this.result = this.value.split(",");
    } else {
      this.result = [];
    }

    this.$watch(
      "result",
      val => {
        if (val.length) {
          this.$emit("input", val.join(","));
        } else {
          this.$emit("input", "");
        }
      },
      { deep: true }
    );
  },
  beforeDestroy() {
    console.log("before destroy");
    this.xhr.abort();
  },
  data() {
    return {
      key: "",
      bucket: "wxbox",
      token: "",
      url: "//upload.qiniu.com/",
      currentFile: {},
      result: [],
      imageSrc: "",
      cropImg: "",
      theFile: {},
      showCropper: false,
      uploadStatus: 0, // 0 未开始 1 上传中 2 已上传
      uploadPercent: 0,
      xhr: {
        abort: () => {}
      },
      persistentOps: "vframe/jpg/offset/1/w/300/h/300",
      localUpload: false
    };
  },
  computed: {
    ...mapGetters({}),
    // headers() {
    //   return {
    //     token: window.sessionStorage.getItem("token"),
    //     clientId: "ADMIN"
    //   };
    // },
    acceptType() {
      switch (this.accept) {
        case "video":
          return "video/*";
        case "audio":
          return "audio/*";
        default:
          return "*/*";
      }
    },
    acceptTypeText() {
      switch (this.accept) {
        case "video":
          return "视频";
        case "audio":
          return "音频";
      }
    },
    videoSource() {
      return [
        {
          type: "video/mp4",
          src: this.$options.filters.fullImagePath(this.result[0])
        }
      ];
    }
  },
  watch: {
    value(val) {
      if (val.length) {
        this.result = val.split(",");
      } else {
        this.result = [];
      }
    }
  },
  methods: {
    selectFile: async function(e) {
      const file = e.target.files[0];
      this.currentFile = file;

      if (this.result.length >= this.multi) {
        this.$refs.userfile.value = null;
        // this.$emit("on-error", { message: `最多上传${this.multi}个文件` });
        this.$notify({
          title: `最多上传${this.multi}个文件`,
          type: "danger"
        });
        return false;
      }

      const isAcceptType = new RegExp(this.acceptType, "i").test(file.type);

      if (!isAcceptType) {
        this.$refs.userfile.value = null;
        // this.$emit("on-error", {
        //   message: `请选择${this.acceptTypeText}类型文件`
        // });
        this.$notify({
          title: `请选择${this.acceptTypeText}类型文件`,
          type: "danger"
        });
        return false;
      }

      if (file.size > this.maxSize * 1000) {
        this.$refs.userfile.value = null;
        // this.$emit("on-error", {
        //   message: `请上传小于${this.maxSize}KB的文件`
        // });
        this.$notify({
          title: `请上传小于${this.maxSize / 1024}MB的文件`,
          type: "danger"
        });
        return false;
      }

      var tmp = `${file.lastModified + file.size + Date.now()}`;
      var nameArr = file.name.split(".");
      var extName = nameArr[nameArr.length - 1];
      this.key = md5(tmp).substr(0, 10) + "." + extName;

      if (this.localUpload) {
        this.token = window.sessionStorage.getItem("token");
      } else {
        this.token = await this.getToken(this.key);
      }
      this.$emit("on-selected", file);

      switch (this.accept) {
        case "video":
        case "audio":
          {
            console.log(this.token, this.key);
            let url = await this.uploadFile(file);
            console.log("url:", url);
          }

          break;
      }
    },
    uploadFile(file) {
      this.uploadStatus = 1;
      var fd = new FormData();
      fd.append("token", this.token);
      fd.append("key", this.key);
      fd.append("file", file);
      console.log(1222);
      return axiosInstance({
        method: "POST",
        url: this.$appConf.domain.uploadUrl,
        data: fd,
        onUploadProgress: progressEvent => {
          this.uploadPercent = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(this.uploadPercent);
        }
      })
        .then(res => {
          console.log("res", res);
          Api.clientUploadSuccess({
            key: res.data.key,
            persistentId: res.data.persistentId
          }).then(ret => {
            this.uploadStatus = 2;
            if (this.localUpload) {
              this.result.push(res.data.data.fileName);
              this.$refs.userfile.value = null;
              return res.data.data.fileUrl;
            } else {
              this.result.push(res.data.key);
              this.$refs.userfile.value = null;
              return `${window.api.imageDomain}${res.data.key}`;
            }
          });
        })
        .catch(err => {
          console.log("err", err);
          this.clean();
        });
    },
    progress(e) {
      if (e.lengthComputable) {
        this.uploadPercent = (e.loaded / e.total) * 100;
        console.log(this.uploadPercent);
      }
    },
    clean() {
      this.$confirm("确认删除该文件吗?", "提示", {})
        .then(() => {
          this.$refs.userfile.value = null;
          this.result = [];
          this.uploadStatus = 0;
          this.uploadPercent = 0;
          this.$emit("on-clean");
        })
        .catch(() => {});
    },
    getToken(key) {
      this.persistentOps =
        "vframe/jpg/offset/1/w/" + this.width + "/h/" + this.height;
      return Api.getUploadFileToken({
        fileName: key,
        persistentOps: this.persistentOps
      }).then(ret => {
        this.key = ret.data.data.key;
        return ret.data.data.token;
      });
    }
  },
  components: {
    AudioPlayer,
    MyVideo,
    CloseBtn
  }
};
</script>
<style>
.upload-button > * {
  pointer-events: none;
}

.upload-button {
  display: block;
  width: 100%;
  min-height: 150px;
  margin: 10px auto auto auto;
  padding: 10px auto;
  border-radius: 10px;
  border: 2px dashed #ddd;
  overflow: hidden;
  cursor: pointer;
}

.upload-button span {
  display: block;
  width: 50px;
  height: 50px;
  border-radius: 100%;
  border: 3px solid #0983c7;
  margin: 30px auto 15px;
  position: relative;
}

.upload-button em {
  font-style: normal;
  text-align: center;
  display: block;
}

.upload-button span:before,
.upload-button span:after {
  display: block;
  content: "";
  background-color: #0983c7;
  position: absolute;
}

.upload-button span:before {
  width: 3px;
  height: 30px;
  top: 10px;
  left: 24px;
}

.upload-button span:after {
  width: 30px;
  height: 3px;
  top: 24px;
  left: 10px;
}

.audio-preview {
  width: 100%;
  position: relative;
}

.video-preview {
  width: 100%;
  position: relative;
}

.delete-btn {
  top: -8px;
  right: -5px;
  position: absolute !important;
  cursor: pointer;
}
</style>
